package ac.beiwo.baas.common.controller;

import ac.beiwo.baas.common.entity.SimpleError;
import ac.beiwo.baas.common.entity.SimpleCode;
import ac.beiwo.baas.common.entity.SimpleResult;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * Created by Staryet on 15/6/17.
 */
@ControllerAdvice
public class ErrorController {

    private Log log = LogFactory.getLog(getClass());

    @ExceptionHandler(SimpleError.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public SimpleResult errorResponse(SimpleError e) {
        return SimpleResult.fromError(e);
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public SimpleResult errorResponse(HttpMessageNotReadableException t) {
        log.error(t, t);
        return new SimpleResult(SimpleCode.REQUEST_PARAM_ERROR);
    }

    @ExceptionHandler(Throwable.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public SimpleResult errorResponse(Throwable t) {
        log.error(t, t);
        return new SimpleResult(SimpleCode.INTENAL_ERROR);
    }

}
